package com.csx.governance.traffic.condition;

import cn.hutool.core.util.StrUtil;
import com.csx.governance.traffic.condition.support.ExpressionExecutors;

import java.util.Collection;
import java.util.Collections;
import java.util.stream.Collectors;

/**
 * @author cuisongxu
 * @date 2023/2/25 11:26
 */
public class ComponentsCompiler {

    public static final ComponentsCompiler EMPTY = new ComponentsCompiler();

    private Collection<? extends Component> expressionComponents = Collections.emptyList();

    public ComponentsCompiler(Collection<? extends Component> expressionComponents) {
        this.expressionComponents = expressionComponents;
    }

    private ComponentsCompiler() {

    }

    private String getExpressionStatement() {
        return this.expressionComponents.stream()
                .map(Component::getStatement)
                .collect(Collectors.joining(" "));
    }

    public ParsedExpression parse() {
        String statement = this.getExpressionStatement();
        if(StrUtil.isBlank(statement)) {
            return null;
        }
        /**
         * 缓存编译后的表达式
         */
        return ExpressionExecutors.FIRST_EXPRESSION_EXECUTOR.parse(statement);
    }
}
